import { _decorator, CCInteger, Component, Label, Node } from 'cc';
import { PoolFactory } from '../../Basic/Component/PoolFactory';
import { PoolElementType } from '../Config/GameEnum';
import { PropItem } from './PropItem';
import { GameModel } from './GameModel';
const { ccclass, property } = _decorator;

@ccclass('PropMachine')
export class PropMachine extends Component {
  @property(Node)
  cellItem: Node;
  @property(Node)
  propParent: Node;
  @property(PoolFactory)
  poolFac: PoolFactory;
  @property(CCInteger)
  maxWidth: number;
  propItems: PropItem[];
  curCellCount: number;
  constructor() {
    super();
    this.curCellCount = 0;
    this.propItems = [];
  }

  /** 初始化道具列表 */
  initPropList(propId: string[] = []) {
    const sumCount = propId.length + 1;
    const space = this.maxWidth / sumCount;
    this.cellItem.setPosition((-(sumCount - 1) / 2) * space, 0);
    for (let i = 0; i < propId.length; i++) {
      const item = this.poolFac.pop(PoolElementType.PROP_ITEM, 'maingame/game', 'PropItem');
      const script = item.getComponent(PropItem);
      script.setData(propId[i]);
      this.propItems.push(script);
      this.propParent.addChild(item);
      item.setPosition((-(sumCount - 1) / 2) * space + (i + 1) * space, 0);
    }
    this.refreshGridCount();
  }

  refreshAllProp() {
    this.propItems.forEach((item) => {
      item.rendererUI();
    });
  }

  /** 刷新剩余步数 */
  refreshGridCount() {
    const circle = this.cellItem.getChildByName('circle');
    const count = this.cellItem.getChildByName('count').getComponent(Label);
    circle.active = GameModel.Ins().curGridCount >= 0;
    count.node.active = GameModel.Ins().curGridCount >= 0;
    count.string = `${GameModel.Ins().curGridCount}`;
  }

  showAllItem(isShow: boolean) {
    this.cellItem.active = isShow;
    this.propItems.forEach((item) => {
      item.node.active = isShow;
    });
  }

  resetPropList() {
    while (this.propItems.length) {
      const item = this.propItems.pop();
      this.poolFac.push(item.node);
    }
    this.propItems = [];
    this.curCellCount = 0;
  }

  /** 初始化数量 */
  initGridCount(count: number) {
    this.curCellCount = count;
  }

  protected onEnable(): void {
    this.refreshCellItem();
  }

  refreshCellItem() {
    // const cellAdd = this.cellItem.getChildByName('add');
    const cellCount = this.cellItem.getChildByName('count').getComponent(Label);
    // cellAdd.active = this.curCellCount <= 0;
    cellCount.string = `${this.curCellCount}`;
  }

  /** 增加盒子 */
  onClickCellAdd() {
    // 展示弹窗
  }
}
